package com.yx.cloud.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AppOpsManager;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;
import androidx.core.app.AppOpsManagerCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.aliyun.alink.business.devicecenter.api.add.DeviceInfo;
import com.aliyun.alink.business.devicecenter.api.discovery.LocalDeviceMgr;
import com.google.gson.Gson;
import com.iot.base.bean.Product;
import com.iot.base.service.IOTProductManager;
import com.iot.common.utils.Event;
import com.iot.common.utils.LogUtils;
import com.yx.cloud.BuildConfig;
import com.yx.cloud.Interface.OnItemClickListener;
import com.yx.cloud.R;
import com.yx.cloud.adapter.BluetoothListAdapter;
import com.yx.cloud.adapter.SelectSeriesAdapter;
import com.yx.cloud.base.BaseActivity;
import com.yx.cloud.constant.Constants;
import com.yx.cloud.databinding.AddequipmentActivityBinding;
import com.yx.cloud.network.ble.BluetoothModel;
import com.yx.cloud.product.ProductConfigConstants;
import com.yx.cloud.product.laser.inxni.INXNIConstant;
import com.yx.cloud.product.laser.tuyapublic.BluetoothScanDeviceBean;
import com.yx.cloud.product.laser.yxcloud.X3_FULL;
import com.yx.cloud.product.laser.yxcloud.X3_MAX;
import com.yx.cloud.product.laser.yxcloud.X3_PLUS;
import com.yx.cloud.product.laser.yxcloud.X3_YXCLOUD;
import com.yx.cloud.product.laser.yxcloud.X5_MAX;
import com.yx.cloud.product.sdk.tmall.AliGenieSdk;
import com.yx.cloud.utils.AppUtil;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.utils.SharedPrefsUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class AddEquipmentActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "AddEquipmentActivity";
    public int REQUEST_CODE_ASK_PERMISSIONS = 1;
    boolean hasPermissionDismiss = false;
    private AddequipmentActivityBinding binding;
    private List<BluetoothScanDeviceBean> le; //蓝牙扫描结果存储
    private BluetoothListAdapter bluetoothAdapter;
    private int curStr = 0;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothScanDeviceBean bsb;
    private boolean tuya = false;
    private boolean ALi = false;
    private List<String> mPermissionList = new ArrayList<>();
    private BluetoothScanDeviceBean deviceBean;
    private String mTmall_userNickname;
    private LinearLayoutManager linearLayoutManager;
    private boolean enable;
    private boolean autoOpenBluetooth = false;
    private boolean doesItExist = false;
    private BluetoothModel model;
    private Dialog permissions_dialog;


    @Override
    public void onCreate() {
        binding = AddequipmentActivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        LogUtils.i("1111111111111111111111 onStart :");
        ALi = false;
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        boolean value = SharedPrefsUtil.getValue(this, "REQUEST_ACCESS", "request_access", false);//保存是否申请过系统权限
        if (!value) {
            permissionApplication();
        } else {
            openBluetooth("start");
        }
        initData();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        LogUtils.i(autoOpenBluetooth + "1111111111111111111111 onWindowFocusChanged :" + hasFocus);
        if (hasFocus) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    runOnUiThread(new Runnable() {
                        @SuppressLint("MissingPermission")
                        @Override
                        public void run() {
                            if (!mBluetoothAdapter.isEnabled()) {
                                binding.rlOpenBluetooth.setVisibility(View.VISIBLE);//开启蓝牙提示布局
                            } else {
                                binding.rlOpenBluetooth.setVisibility(View.GONE);//开启蓝牙提示布局
                            }
                        }
                    });
                }
            }).start();
        }
    }

    private void permissionApplication() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            // Android 版本大于等于 Android12 ?
            mPermissionList.add(Manifest.permission.BLUETOOTH_SCAN);
            mPermissionList.add(Manifest.permission.BLUETOOTH_ADVERTISE);
            mPermissionList.add(Manifest.permission.BLUETOOTH_CONNECT);
            mPermissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
            mPermissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        } else {
            // Android 版本小于 Android12 及以下版?
            mPermissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            mPermissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (mPermissionList.size() > 0) {
            SharedPrefsUtil.putValue(this, "REQUEST_ACCESS", "request_access", true);//保存是否申请过系统权?
            ActivityCompat.requestPermissions(this, mPermissionList.toArray(new String[0]), 1001);
        }
    }

    private void initData() {
        binding.ivX5ScanBg.setVisibility(View.GONE);
        binding.bluetoothListView.setVisibility(View.GONE);//列表布局
        binding.llSearch.setVisibility(View.VISIBLE);//搜索布局
        binding.lottieSearch.playAnimation();
        le = new ArrayList<>();
        le.clear();
        binding.bluetoothListView.setHasFixedSize(true);
        binding.bluetoothListView.setNestedScrollingEnabled(false);

        binding.ivAddEquipmentReturn.setOnClickListener(this);
        binding.rlOpenBluetooth.setOnClickListener(this);

        bluetoothAdapter = new BluetoothListAdapter(this, le);
        linearLayoutManager = new LinearLayoutManager(this);
        binding.bluetoothListView.setLayoutManager(linearLayoutManager);
        binding.bluetoothListView.setAdapter(bluetoothAdapter);

        bluetoothAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                SharedPrefsUtil.putValue(AddEquipmentActivity.this, "ROBOT_SERIES", "robot_series", "bluetooth");//给配网失败后返回使用
                deviceBean = le.get(position);
                String source = deviceBean.getSource();//区分蓝牙扫描出来的设备 是X5 基站还是其他机型的
                LogUtils.i("选择的设备型号 deviceBean.getName() : " + deviceBean.getName());

                String deviceType = ProductConfigConstants.getNetworkDeviceType(deviceBean.getName());//根据选择的机型设置设备类型
                LogUtils.i("选择的设备型号 deviceType : " + deviceType);
                if ("yugong".equals(source)) {
                    Intent select = new Intent(AddEquipmentActivity.this, SelectWIFIActivity.class);
                    select.putExtra("network", "bluetooth");
                    select.putExtra("source", "other");
                    select.putExtra("bluetoothData", deviceBean);
                    select.putExtra("device_type", deviceType);//设备型号
                    startActivity(select);
                } else {
                    //已经登录成功了，不在进行登录直接进行绑定
                    mTmall_userNickname = SharedPrefsUtil.getValue(AddEquipmentActivity.this, "TMALL_ALIGENIE_USER_INFO", "tmall_aligenie_user_info", "");
                    INXNIConstant.TMALL_USER_NICK_NAME = mTmall_userNickname;
                    if ("".equals(mTmall_userNickname)) {
                        Intent select = new Intent(AddEquipmentActivity.this, BindTaobaoAccountActivity.class);
                        select.putExtra("network", "bluetooth");
                        select.putExtra("bluetoothData", deviceBean);
                        select.putExtra("device_type", deviceType);//设备型号
                        startActivity(select);
                    } else {
                        Intent intent = new Intent(AddEquipmentActivity.this, TmallUnbindUserActivity.class);
                        intent.putExtra("network", "bluetooth");
                        intent.putExtra("source", "X5");
                        intent.putExtra("nickname", INXNIConstant.TMALL_USER_NICK_NAME);
                        intent.putExtra("bluetoothData", deviceBean);//保存的X5蓝牙信息
                        intent.putExtra("device_type", deviceType);//设备型号
                        startActivity(intent);
                    }
                }
            }
        });

        //*********************手动***************************//
        String[] strProduct = ProductConfigConstants.deviceList();
        SelectSeriesAdapter selectSeriesAdapter = new SelectSeriesAdapter(this, strProduct);
        GridLayoutManager layoutManager = new GridLayoutManager(this, 1);
        binding.rvSelectSeries.setLayoutManager(layoutManager);
        binding.rvSelectSeries.setAdapter(selectSeriesAdapter);
        selectSeriesAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
//                LogUtils.d("选择的机器型号 :" + SelectSeriesList.get(position));
                if (strProduct[position].equals("tmall")) {
                    boolean tmallInstalled = AppUtil.isPkgInstalled(AddEquipmentActivity.this, "com.alibaba.ailabs.tg");
                    if (tmallInstalled) {
                        runTmallApp("com.alibaba.ailabs.tg");
                    } else {
                        tmallAPPInstallHintDialog(getString(R.string.N_Tmall_Not), getString(R.string.N_Tmall_Not_Tip));
                    }
                } else {
                    String deviceType = ProductConfigConstants.getNetworkDeviceType(strProduct[position]);//根据选择的机型设置设备类型
                    Intent selectseries = new Intent(AddEquipmentActivity.this, SelectSeriesActivity.class);
                    SharedPrefsUtil.putValue(AddEquipmentActivity.this, "ROBOT_SERIES", "robot_series", "other");//给配网失败后返回使用
//                    Log.i(TAG, deviceType + " ; 1111111111111111111111 robot_type :" + strProduct[position]);
                    selectseries.putExtra("switchNetwork", "add");
                    selectseries.putExtra("device_type", deviceType);//设备型号
                    startActivity(selectseries);
                }
            }
        });
    }

    @SuppressLint("MissingPermission")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        switch (event.getType()) {
            case Event.MESSAGE_TYPE_TUYA_BLUETOOTH_SCAN:
                //蓝牙扫描回调
                BluetoothDevice device = (BluetoothDevice) event.getContent();
                if (le.size() > 0) {
                    for (int i = 0; i < le.size(); i++) {
                        if (device.getAddress().equals(le.get(i).getAddress())) {
                            doesItExist = true;
                        }
                    }
                }
                if (!doesItExist) {
                    binding.lottieSearch.pauseAnimation();//搜索动画停止
                    binding.bluetoothListView.setVisibility(View.VISIBLE);//列表布局
                    binding.ivX5ScanBg.setVisibility(View.VISIBLE);
                    binding.llSearch.setVisibility(View.GONE);//搜索布局
                    LogUtils.d("yugong Bluetooth scan  :::::::::::::::::::::::::: " + new Gson().toJson(device));
                    scanDataPackage("yugong", device, null);
                    bluetoothAdapter.notifyDataSetChanged();
                }
                doesItExist = false;
                break;
            case Event.MESSAGE_TYPE_TMALL_BLUETOOTH_SCAN:
                //天猫精灵蓝牙扫描回调
                List<DeviceInfo> list = (List<DeviceInfo>) event.getContent();
                LogUtils.d("阿里 Bluetooth scan  :::::::::::::::::::::::::: " + list.toString());
                if (list.size() > 0) {
                    if (le.size() == 0) {
                        if (!ALi) {
                            for (int j = 0; j < list.size(); j++) {
                                DeviceInfo deviceInfo_j = list.get(j);
                                scanDataPackage("ali", null, deviceInfo_j);
                            }
                            bluetoothAdapter.notifyDataSetChanged();
                            ALi = false;
                        }
                    } else {
                        for (int ii = 0; ii < list.size(); ii++) {
                            DeviceInfo info = list.get(ii);
                            String mac1 = info.mac;
                            for (int j = 0; j < le.size(); j++) {
                                if (mac1.equals(le.get(j).getMac())) {
                                    //说明已经存在了
                                    ALi = true;
                                }
                            }
                        }
                        if (!ALi) {
                            for (int iii = 0; iii < list.size(); iii++) {
                                DeviceInfo deviceInfo_iii = list.get(iii);
                                scanDataPackage("ali", null, deviceInfo_iii);
                            }
                            bluetoothAdapter.notifyDataSetChanged();
                            ALi = false;
                        }
                    }
                }
                break;
        }
    }

    @SuppressLint("MissingPermission")
    private void scanDataPackage(String source, BluetoothDevice bean, DeviceInfo deviceInfo) {
        if ("yugong".equals(source)) {
            bsb = new BluetoothScanDeviceBean();
            bsb.setSource("yugong");
            bsb.setAddress(bean.getAddress());
            String name = bean.getName();
            LogUtils.i(" yugong Bluetooth scan  44444:::::::::::::::::::::::::: " + bean.getName());
            bsb.setName(name);
            le.add(bsb);
        } else {
            LogUtils.d("阿里 scanDataPackage  :::::::::::::::::::::::::: ");
            bsb = new BluetoothScanDeviceBean();
            bsb.setSource("ali");
            bsb = new BluetoothScanDeviceBean();
            bsb.setDeviceId(deviceInfo.deviceId);
            bsb.setDeviceName(deviceInfo.deviceName);
            bsb.setMac(deviceInfo.mac);
            bsb.setProductId(deviceInfo.productId);
            bsb.setProductKey(deviceInfo.productKey);
            bsb.setUserId(deviceInfo.userId);
            bsb.setName("X5Max");
            Map extraDeviceInfo = deviceInfo.getExtraDeviceInfo();
            String info = getExtraDeviceInfo(extraDeviceInfo);
            bsb.setExtraDeviceInfo(info);
            le.add(bsb);
        }
        //isSearch = false;//子线程循环标记
        binding.lottieSearch.pauseAnimation();//搜索动画停止
        binding.bluetoothListView.setVisibility(View.VISIBLE);//列表布局
        binding.llSearch.setVisibility(View.GONE);//搜索布局
        binding.ivX5ScanBg.setVisibility(View.VISIBLE);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.i(TAG, "权限设置返回----------------------------------------------------" + requestCode);
        if (grantResults.length > 0 && requestCode == REQUEST_CODE_ASK_PERMISSIONS && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//            initData();
            Constants.PERISSION = true;
            Log.i(TAG, "打开了GPS");
        } else if (1001 == requestCode) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == -1) {
                    hasPermissionDismiss = true;
                    break;
                }
            }
            Log.i(TAG, "权限设置返回-----------1111----------------------------------------" + hasPermissionDismiss);
            if (hasPermissionDismiss) {
                // 有权限未通过的处理
                checkLocationPermission();
            } else {
                //权限全部通过的处理，打开蓝牙
                openBluetooth("result");
            }
        } else {
            locatePermissionsDialog("GPS", getString(R.string.N_Position_Open), getString(R.string.N_Position_Open_Tip));
            //ToastUtil.showLong(SelectWIFIActivity.this, "请检查手机应用权限管理中是否授权");
            Log.i(TAG, "没有打开了GPS");
        }
    }

    @SuppressLint("MissingPermission")
    private void openBluetooth(String tag) {
        if (!AppUtil.isLocServiceEnable(this)) {//检测是否开启定位服务
            //未开启定位服务的操作
            LogUtils.i("--------------------------------未开启定位服务的操作");
            locatePermissionsDialog("locationInformation", getString(R.string.N_Position_Open), getString(R.string.N_Position_Open_Tip));
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                //检测用户是否将当前应用的定位权限拒绝
                int checkResult = AppUtil.checkOp(this, 2, AppOpsManager.OPSTR_FINE_LOCATION);//其中2代表AppOpsManager.OP_GPS，如果要判断悬浮框权限，第二个参数需换成24即AppOpsManager。OP_SYSTEM_ALERT_WINDOW及，第三个参数需要换成AppOpsManager.OPSTR_SYSTEM_ALERT_WINDOW
                int permission2 = ActivityCompat.checkSelfPermission(AddEquipmentActivity.this, Manifest.permission.BLUETOOTH_SCAN);//蓝牙扫描或WIFI扫描时需要的附近设备权限
                if (AppOpsManagerCompat.MODE_IGNORED == checkResult) {
                    //未开启定位权限或者被拒绝的操作
                    LogUtils.i("--------------------------------未开启GPS服务的操作");
                    locatePermissionsDialog("GPS", getString(R.string.N_Position_Open), getString(R.string.N_Position_Open_Tip));
                } else if (permission2 != PackageManager.PERMISSION_GRANTED) {
                    LogUtils.i("--------------------------------未开启开启附近的设备");
                    locatePermissionsDialog("GPS", getString(R.string.N_Attached_Open), getString(R.string.N_Attached_Open_Tip));
                } else {
                    if ("bleSwitch".equals(tag)) {
                        //开启蓝牙开关
                        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                        enableBtIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(enableBtIntent);
                    }
                    if (!mBluetoothAdapter.isEnabled()) {
                        binding.rlOpenBluetooth.setVisibility(View.VISIBLE);//开启蓝牙提示布局
                    } else {
                        //所以权限都有了
                        binding.rlOpenBluetooth.setVisibility(View.GONE);//开启蓝牙提示布局
                        LogUtils.i("------------------2222--------------所以权限都有了");
                        startScan();
                    }
                }
            } else {
                //?测用户是否将当前应用的定位权限拒?//其中2代表AppOpsManager.OP_GPS，如果要判断悬浮框权限，第二个参数需换成24即AppOpsManager。OP_SYSTEM_ALERT_WINDOW及，第三个参数需要换成AppOpsManager.OPSTR_SYSTEM_ALERT_WINDOW
                int checkResult = AppUtil.checkOp(this, 2, AppOpsManager.OPSTR_FINE_LOCATION);
                if (AppOpsManagerCompat.MODE_IGNORED == checkResult) {
                    //未开启定位权限或者被拒绝的操?
                    LogUtils.i("--------------------------------未开启GPS服务的操?");
                    locatePermissionsDialog("GPS", getString(R.string.N_Attached_Open), getString(R.string.N_Attached_Open_Tip));
                } else {
                    if ("bleSwitch".equals(tag)) {
                        //开启蓝牙开关
                        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                        enableBtIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(enableBtIntent);
                    }
                    if (!mBluetoothAdapter.isEnabled()) {
                        binding.rlOpenBluetooth.setVisibility(View.VISIBLE);//?启蓝牙提示布?
                    } else {
                        //?以权限都有了
                        binding.rlOpenBluetooth.setVisibility(View.GONE);//?启蓝牙提示布?
                        LogUtils.i("-------------------------222-------?以权限都有了");
                        startScan();
                    }
                }
            }

        }
    }

    @SuppressLint("MissingPermission")
    private void startScan() {
        AliGenieSdk.tmallBluetoothScan(AddEquipmentActivity.this);//阿里 开始蓝牙扫描
        model = BluetoothModel.getInstance();
        model.startScanBle(new BluetoothModel.BLEScanCallback() {
            @Override
            public void onDeviceFind(BluetoothDevice device) {
                String name = device.getName();
                LogUtils.i("扫描到的蓝牙设备 : " + name + " ," + device.getAddress());
                if (name == null || (!name.contains("INXNI") && !name.contains("ROBOT-yx"))) {
                    return;
                }
                if (name.contains("X5Max")) {
                    LogUtils.d(" 扫描到了 个x5 扫地机:::::::::::::::::::::::::: ");
                    return;
                }
                LogUtils.i("--------------------------------扫描到了: " + name + " ," + device.getAddress());
                //model.stopScanBle();
                Event.newBuilder().type(Event.MESSAGE_TYPE_TUYA_BLUETOOTH_SCAN).content(device).send();
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        //isSearch = false;//子线程循环标记
        if (model != null) {
            model.stopScanBle();
            LocalDeviceMgr.getInstance().stopDiscovery();//天猫停⽌设备发现
        }
        binding.lottieSearch.pauseAnimation();//搜索动画停止
        // LocalDeviceMgr.getInstance().stopDiscovery();//天猫停⽌设备发现
//        AppContext.getService().tuyaStopLeScan();//涂鸦停止扫描
    }

    private void runTmallApp(String packageName) {
        try {
            Intent intent = getPackageManager().getLaunchIntentForPackage(packageName);
            startActivity(intent);
        } catch (Exception e) {
            LogUtils.i("-------------------没有安装该 应用");
        }
    }

    private void tmallAPPInstallHintDialog(String dialogTitle, String content) {
        Dialog dialog = new Dialog(AddEquipmentActivity.this);
        dialog.setContentView(R.layout.outlogin_dialog);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.setCanceledOnTouchOutside(false);
        TextView mBtnOutLoginConfirm = dialog.findViewById(R.id.btn_outLoginConfirm);
        TextView mBtnOutLoginCancel = dialog.findViewById(R.id.btn_outLoginCancel);
        TextView mTvDialogTitle = dialog.findViewById(R.id.tv_dialogTitle);
        TextView mTvDialogContent = dialog.findViewById(R.id.tv_content);
        View vLine = dialog.findViewById(R.id.main_view);
        mTvDialogTitle.setText(dialogTitle);
        mTvDialogContent.setText(content);
        mBtnOutLoginConfirm.setText(getString(R.string.U_IKnow_Btn));
        mBtnOutLoginConfirm.setTextColor(getColor(R.color.text_color_blue));
        mBtnOutLoginCancel.setVisibility(View.GONE);
        vLine.setVisibility(View.GONE);
        mBtnOutLoginConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                dialog.dismiss();
            }
        });
        dialog.show();
    }


    private void checkLocationPermission() {
        int permission_1 = ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN);
        boolean permission_2 = ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.BLUETOOTH_SCAN);
        if (permission_1 == -1 && permission_2) {
            //拒绝权限，但不是永久拒绝
            //Log.d(TAG, " : MenuAddDeviceFragment======拒绝权限，但不是永久拒绝========= : ");
            //蓝牙已开启
            check_location_services_enabled();
        } else if (permission_1 == -1 && !permission_2) {
            //拒绝权限，是永久拒绝
            //Log.d(TAG, " : MenuAddDeviceFragment======拒绝权限，是永久拒绝========= : ");
            check_location_services_enabled();
        } else if (permission_1 == 0 && !permission_2) {
            //权限都有了
            //Log.d(TAG, " : MenuAddDeviceFragment======权限都有了========= : ");
        }
    }

    private void check_location_services_enabled() {
        if (!AppUtil.isLocServiceEnable(this)) {//检测是否开启定位服务
            //未开启定位服务的操作
            LogUtils.i("--------------------------------未开启定位服务的操作");
            locatePermissionsDialog("locationInformation", getString(R.string.N_Position_Open), getString(R.string.N_Position_Open_Tip));
        } else {
            //检测用户是否将当前应用的定位权限拒绝
            int checkResult = AppUtil.checkOp(this, 2, AppOpsManager.OPSTR_FINE_LOCATION);//其中2代表AppOpsManager.OP_GPS，如果要判断悬浮框权限，第二个参数需换成24即AppOpsManager。OP_SYSTEM_ALERT_WINDOW及，第三个参数需要换成AppOpsManager.OPSTR_SYSTEM_ALERT_WINDOW
            if (AppOpsManagerCompat.MODE_IGNORED == checkResult) {
                //未开启定位权限或者被拒绝的操作
                LogUtils.i("--------------------------------未开启定位权限或者被拒绝的操作");
                locatePermissionsDialog("GPS", getString(R.string.N_Position_Open), getString(R.string.N_Position_Open_Tip));
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    int permission2 = ActivityCompat.checkSelfPermission(AddEquipmentActivity.this, Manifest.permission.BLUETOOTH_SCAN);//蓝牙扫描或WIFI扫描时需要的附近设备权限
                    if (PackageManager.PERMISSION_GRANTED != permission2) {
                        LogUtils.i("--------------------------------未开启开启附近的设备");
                        locatePermissionsDialog("GPS", getString(R.string.N_Attached_Open), getString(R.string.N_Attached_Open_Tip));
                    }
                }
            }
        }
    }

    private void locatePermissionsDialog(String type, String title, String content) {
        if (permissions_dialog != null && permissions_dialog.isShowing()) {
            permissions_dialog.dismiss();
        }
        permissions_dialog = new Dialog(AddEquipmentActivity.this);
        permissions_dialog.setContentView(R.layout.location_permissions_dialog);
        permissions_dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        permissions_dialog.setCanceledOnTouchOutside(false);
        TextView mBtnLocationConfirm = permissions_dialog.findViewById(R.id.btn_location_Confirm);
        TextView mBtnLocationCancel = permissions_dialog.findViewById(R.id.btn_location_Cancel);
        TextView mTvLocationPermissionsTypeTitle = permissions_dialog.findViewById(R.id.tv_locationPermissionsTypeTitle);
        TextView mTvLocationPermissionsTypeContent = permissions_dialog.findViewById(R.id.tv_locationPermissionsTypeContent);
        mTvLocationPermissionsTypeTitle.setText(title);
        mTvLocationPermissionsTypeContent.setText(content);
        mBtnLocationConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //定位
                if (type.equals("GPS")) {
//                    int permission2 = ActivityCompat.checkSelfPermission(AddEquipmentActivity.this, Manifest.permission.BLUETOOTH_SCAN);//蓝牙扫描或WIFI扫描时需要的附近设备权限
//                    if (permission2 != PackageManager.PERMISSION_GRANTED) {
//                        ToastUtil.show(AddEquipmentActivity.this, getString(R.string.nearby_devices), Toast.LENGTH_LONG);
//                    }
                    Intent mIntent = new Intent();
                    mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    mIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                    mIntent.setData(Uri.fromParts("package", getPackageName(), null));
                    startActivityForResult(mIntent, 888);
                } else {
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(intent, 887);
                }
                permissions_dialog.dismiss();
            }
        });
        mBtnLocationCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                permissions_dialog.dismiss();
            }
        });
        permissions_dialog.show();
    }

    private String getExtraDeviceInfo(Map extraDeviceInfo) {
        String json = new Gson().toJson(extraDeviceInfo);
        JSONObject jsonObject = null;
        String netConfigFlag = null;
        try {
            jsonObject = new JSONObject(json);
            JSONObject object = jsonObject.getJSONObject("ble_discovered_device");
            netConfigFlag = object.getString("netConfigFlag");
            // if ("iLHk".equals(netConfigFlag)) {
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return netConfigFlag;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            LogUtils.i("1111111111111111111111 onKeyDown  onKeyDown:");
            Intent_utils.backIntent(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void onClick(View v) {
        if (RomUtils.isFastClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.iv_addEquipment_return:
                Intent_utils.backIntent(this);
                break;
            case R.id.rl_openBluetooth:
                //若没打开则打开蓝牙
                autoOpenBluetooth = true;
                openBluetooth("bleSwitch");
//                List<String> mPermissionList = new ArrayList<>();
//                mPermissionList.add(Manifest.permission.BLUETOOTH_CONNECT);
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
//                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
//                        ActivityCompat.requestPermissions(this, mPermissionList.toArray(new String[0]), 1003);
//                    }
//                }
//                if (!mBluetoothAdapter.isEnabled()) {
//                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//                    enableBtIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    startActivity(enableBtIntent);
//                }
                break;
        }
    }
}